package com.yyaccp.hncc.smsg.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yyaccp.hncc.smsg.service.ShortMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云短信实现
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/9/8.
 */
@Service("aliyunSms")
@Slf4j
@Primary
@ConditionalOnProperty(name = "sms.provider", havingValue = "aliyun")
public class ShortMessageServiceAliyunImpl implements ShortMessageService {
    @Value("${sms.aliyun.validCodeTemplateId}")
    private String validCodeTemplateId;

    @Override
    public String sendValidCodeMessage(String phoneNumbers, String code) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("code", code);
        return sendMessage(phoneNumbers, validCodeTemplateId, paramsMap);
    }

    @Override
    public String sendMessage(String phoneNumbers,String templateId, Map<String, String> paramsMap) {
        String result = SUCCESS;
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4Fn7qwJ6XrtsugWY8X1G", "whG0UglJWJs0Wctd2moIGTocRhj9bl");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", "岳阳海纳");
        request.putQueryParameter("TemplateCode", templateId);
        try {
            request.putQueryParameter("TemplateParam", new ObjectMapper().writeValueAsString(paramsMap));
        } catch (JsonProcessingException e) {
            result = "解析模板参数异常";
            log.error(result, e);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            result = "连接aliyun服务器异常";
            log.error(result, e);
        } catch (ClientException e) {
            result = "客户端异常";
            log.error(result, e);
        }
        return result;
    }
}
